<template>
    <div class="body">
        <van-sticky>
            <van-nav-bar title="购物车" />
            <van-notice-bar left-icon="volume-o" text="各类绝版商品售出 快点推荐你的耗油们来买吧!!! 对自己好点 什么情啊爱啊都是浮云" />
        </van-sticky>
        <!-- 购物车没有商品的时候不展示  -->
        <div v-if="cartGoodslist.length > 0">
            <div v-if="hasaddress" class="header" style="display: flex;justify-content: space-around;margin-top: 12px;">
                <van-icon name="free-postage" style="font-size:30px" />
                <div @click="$router.push('/address')">
                    <div>{{ address.name }} &nbsp;/&nbsp; {{ address.tel }} &nbsp;/&nbsp;邮编: {{ address.postalCode }}
                    </div>
                    <div>{{ address.province }}&nbsp;{{ address.city }}&nbsp;
                        {{ address.country }}&nbsp;{{ address.addressDetail }}
                    </div>
                </div>
            </div>
            <!-- 无设置收货地址 -->
            <van-button v-else block type="danger" @click="$router.push('/addaddress')">添加地址</van-button>
        </div>

        <van-divider />
        <!-- <van-contact-card type="edit" :name="address.name" :tel="address.tel" :cty="address.city" :editable="false" /> -->

        <div class="shoplist" style="margin-bottom: 100px;">
            <!-- {{ $store.getters.getCarGoodsIds }} -->
            <!-- <div class="carlist"> -->
            <van-swipe-cell v-for="(item, index) in cartGoodslist" :key="item.id"
                style="margin-top: 10px;background-color: #fafafa;">
                <div class="checkbox" style="display:flex">
                    <van-checkbox @click="checkBoxChange(item.id, $store.getters.getGoodsStatusById[item.id])"
                        v-model="$store.getters.getGoodsStatusById[item.id]" icon-size="24px" checked-color="#ee0a24" />
                </div>
                <van-card :price="item.sell_price" :title="item.title" class="goods-card" :thumb="item.thumb_path">
                    <template #price-top>
                        <!-- 绑定购物车数量 -->
                        <van-stepper @change="numberChange($event, item.id)"
                            v-model="$store.getters.getGoodsNumberById[item.id]" theme="round" button-size="22"
                            disable-input />
                    </template>
                </van-card>

                <template #right>
                    <!-- <van-button square text="删除" type="danger" class="delete-button" /> -->
                    <button style="background-color: red;color: aliceblue;border: none;"
                        @click="delCartGoods(item.id, index)">删除</button>
                </template>
            </van-swipe-cell>
            <!-- </div> -->
        </div>

        <van-submit-bar class="TJ" :price="$store.getters.getTotalPrice * 100" button-text="提交订单"
        :disabled="cartGoodslist.length === 0 || !hasaddress || !$store.getters.getCarSelectGoodsIds"
        @submit="gosubmit">
            <template #default>共选中 {{ $store.getters.getCarSelectedTotalNumber }} 件</template>
        </van-submit-bar>

        <!-- 购物车没有商品的时候展示 -->
        <div style="margin-top: -20px;" v-if="cartGoodslist.length === 0">
            <!-- <van-notice-bar left-icon="volume-o" text="多买点 对自己好点 什么情啊爱啊都是浮云" /> -->
            <van-empty image="https://img01.yzcdn.cn/vant/custom-empty-image.png" description="暂无商品 去首页逛逛叭">
                <van-button style="background-color:#ee0a24;color:#fff" @click="$router.push('/home')">去首页</van-button>
            </van-empty>
        </div>

    </div>
</template>

<script>
import { fetchCartGoods } from '../api/index.js'
import { fetchGetUserAddress } from "../api/address";
import { fetchCommitOrder } from "../api/order.js";
import { num } from "../util/num.js";
export default {
    data() {
        return {
            cartGoodslist: [],
            ids: this.$store.getters.getCarGoodsIds,
            hasaddress: false,
            address: {},
        };
    },
    created() {
        this._fetchCartGoods()
        this._fetchGetUserAddress()
    },
    methods: {
        async _fetchCartGoods() {
            //购物车没有商品则不请求
            if (!this.ids) {
                return;
            }
            console.log(this.ids)
            let { message } = await fetchCartGoods(this.ids);
            this.cartGoodslist = message;
            console.log(message);
        },
        async _fetchGetUserAddress() {
            //购物车没有商品就不请求
            if (!this.ids) {
                return;
            }
            let user_id = this.$store.state.userInfo.id;
            // console.log(userid)
            // 判断是否登录 这里判断token 或者导航守卫中判断
            if (!user_id) {
                this.$dialog.alert({
                    message: '请先登录哦',
                }).then(() => {
                    // on close
                    this.$router.replace('/login')
                });
                return;
            }
            // 用户所有地址
            let useralladdress = await fetchGetUserAddress(user_id);
            // 判断购物车页面有没有地址 
            this.hasaddress = !!useralladdress.length;
            // 在判断用户只有一个地址或者多个地址 如果是用户是一个地址即显示默认的地址
            // 如果刚注册的用户没有地址 就提示用户
            if (!this.hasaddress) {
                this.$dialog({ message: '宝 不要忘了填收货地址哦~' });
                return;
            }
            if (useralladdress.length === 1) {
                this.address = useralladdress[0];
                return;
            }
            // 判断是不是默认收货地址
            let defaultIndex = useralladdress.findIndex(item => item.isDefault === 1);
            if (defaultIndex !== -1) {
                this.address = useralladdress[defaultIndex];
            } else {
                this.address = useralladdress[0];
            }
        },
        // 提交订单
        async gosubmit() {
            console.log('提交')
            let user_id = this.$store.state.userInfo.id;
            if (!user_id) {
                this.$route.push('/login');
                return
            };
            // 订单数据
            let orderData = {
                user_id,
                order_id: num(),
                address_id: this.address.id,
                total_price: this.$store.getters.getTotalPrice,
                number: this.$store.getters.getCarSelectedTotalNumber,
                goods_ids: this.$store.getters.getCarSelectGoodsIds
            };
            console.log(orderData)
            // 提交订单loding信息
            this.$toast.loading({
                duration: 0,
                message: '提交订单中',
                forbidClick: true,
                overlay: true
            });
            // 提交订单接口
            let { message, status } = await fetchCommitOrder(orderData);
            this.$toast(message);
            // 关闭上面的提示
            if (status === 0) {
                // 下单成功要清空原来的购物车数据并跳转订单列表
                this.$store.commit('clearCartData');
                this.$router.replace('/myorder');
            }
            this.$toast.clear();
        },
        // 删除商品
        delCartGoods(id, index) {
            // 删除当前data中的商品
            this.cartGoodslist.splice(index, 1);
            // 还要删除vuex
            this.$store.commit("delCartGoods", id);
            console.log(id, index);
        },
        // 切换选中不选中
        checkBoxChange(id, selected) {
            console.log(id, selected);
            this.$store.commit("setGoodsSeleceted", { id, selected });
        },
        numberChange(number, id) {
            this.$store.commit("setGoodsNumber", { number, id });
        }
    }
}
</script>

<style lang="scss" scoped>
::v-deep .van-card__header {
    margin-bottom: 7px;
}

::v-deep .van-swipe-cell__wrapper {
    display: flex;
}

.van-card__content {
    display: flex;
    justify-content: center;
}

::v-deep .van-swipe-cell__right {
    display: flex;
}

.TJ {
    margin-bottom: 50px;

    ::v-deep .van-submit-bar__button--danger {
        background: #22272e;
    }
}
</style>